package com.zch.client.spring.mqtt.config;

import com.zch.client.spring.mqtt.callback.MqttClientRootCallback;
import com.zch.client.spring.mqtt.client.FastMqttClient;
import com.zch.client.spring.mqtt.condition.MqttClientPresentCondition;
import com.zch.client.spring.mqtt.properties.MqttAutoConfigProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.util.ClassUtils;

import javax.annotation.Resource;

/**
 * ConditionalOnProperty 注解使得prometheus.autoconfigure.enable=true 时，该注解作用的MetricsAutoConfiguration类 才会交给spring管理
 * 也才会执行下面的@Bean 方法
 */
//@Configuration
// 判断prometheus.autoconfigure.enabled的值是否为“true”， matchIfMissing = false：,只在true 时才加载
@ConditionalOnProperty(prefix = "mqtt.autoconfig", name = "enabled", havingValue = "true", matchIfMissing = false)
@EnableConfigurationProperties(value = {MqttAutoConfigProperties.class})
public class MqttClientAutoConfiguration {
    @Resource
    MqttAutoConfigProperties mqttAutoConfigProperties;

    @Bean("fastMqttClient")
   // @ConditionalOnBean(MqttClientRootCallback.class)  // @ConditionalOnBean虽然可以判断MqttClientRootCallback类型的bean
    // 是否存在，但是不会抛出明确的异常，MqttClientPresentCondition 类中可以自己定制自己的条件逻辑！
    @Conditional(MqttClientPresentCondition.class)
    FastMqttClient fastMqttClient(){
        FastMqttClient fastMqttClient = new FastMqttClient();
        fastMqttClient.setMqttAutoConfigProperties(mqttAutoConfigProperties);
        return fastMqttClient;
    }
}
